﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace QW.Found.Filter
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly ILoggerFactory _loggerFactory;
        private readonly IWebHostEnvironment _env;
        private readonly IHttpContextAccessor _accessor;
        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="loggerFactory"></param>
        /// <param name="env"></param>
        /// <param name="accessor"></param>
        public ExceptionFilter(ILoggerFactory loggerFactory,
            IWebHostEnvironment env,
            IHttpContextAccessor accessor)
        {
            _loggerFactory = loggerFactory;
            _env = env;
            _accessor = accessor;
        }
        /// <summary>
        /// 产生异常时
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            IHttpContextAccessor ac = new HttpContextAccessor();
            if (!(context.Exception is BusinessException))
            {
                var logger = _loggerFactory.CreateLogger("ExceptionFilter");
                if (context.Exception.TargetSite != null && context.Exception.TargetSite.ReflectedType != null)
                {
                    logger = _loggerFactory.CreateLogger(context.Exception.TargetSite.ReflectedType);
                }
                logger.LogError(context.Exception, context.Exception.Message);
            }
            //if (_env.IsDevelopment()) { }
        }
    }
}
